#include <iostream>
#include <string>
#include <vector>
#include <memory>

// 备忘录类
class Memento {
private:
    std::string state_; // 保存的状态

public:
    explicit Memento(const std::string& state) : state_(state) {}

    std::string getState() const {
        return state_;
    }
};

// 原发器类
class TextEditor {
private:
    std::string text_; // 当前文本内容

public:
    void write(const std::string& text) {
        text_ += text;
    }

    std::string getText() const {
        return text_;
    }

    // 保存当前状态到备忘录
    std::shared_ptr<Memento> save() const {
        return std::make_shared<Memento>(text_);
    }

    // 从备忘录恢复状态
    void restore(const std::shared_ptr<Memento>& memento) {
        text_ = memento->getState();
    }
};

// 负责人类
class Caretaker {
private:
    std::vector<std::shared_ptr<Memento>> history_; // 保存历史备忘录
    size_t currentIndex_ = 0; // 当前备忘录的索引

public:
    void save(const std::shared_ptr<Memento>& memento) {
        // 删除当前索引之后的历史记录，确保新的状态存储在末尾
        history_.erase(history_.begin() + currentIndex_, history_.end());
        history_.push_back(memento);
        currentIndex_ = history_.size();
    }

    std::shared_ptr<Memento> undo() {
        if (currentIndex_ > 1) {
            currentIndex_--;
            return history_[currentIndex_ - 1];
        }
        return nullptr;
    }

    std::shared_ptr<Memento> redo() {
        if (currentIndex_ < history_.size()) {
            currentIndex_++;
            return history_[currentIndex_ - 1];
        }
        return nullptr;
    }
};

// 客户端代码
int main() 
{
    TextEditor editor;
    Caretaker caretaker;

    // 写入文本
    editor.write("Hello");
    caretaker.save(editor.save()); // 保存状态

    editor.write(", World");
    caretaker.save(editor.save()); // 保存状态

    editor.write("!");
    caretaker.save(editor.save()); // 保存状态

    // 显示当前文本
    std::cout << "Current Text: " << editor.getText() << std::endl;

    // 撤销操作
    auto undoState = caretaker.undo();
    if (undoState) {
            editor.restore(undoState);
            std::cout << "After Undo: " << editor.getText() << std::endl;
        }

    // 再次撤销
    undoState = caretaker.undo();
    if (undoState) {
            editor.restore(undoState);
            std::cout << "After Undo: " << editor.getText() << std::endl;
    }

    // 重做操作
    auto redoState = caretaker.redo();
    if (redoState) {
            editor.restore(redoState);
            std::cout << "After Redo: " << editor.getText() << std::endl;
        }

    return 0;
}